package mudbconnection;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import mudbconnection.DBQuestionnairesService.QuestionnaireMapper;
import muobject.Question;
import muobject.Questionnaire;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

@Component("DBQuestionsService")
public class DBQuestionsService implements DBQuestions{
	private JdbcTemplate jdbct;

	@Autowired
	public DBQuestionsService(DataSource jdbct) {
		super();
		this.jdbct = new JdbcTemplate(jdbct);
	}
	
	public List<Question> getQuestionByYear(String year){
		try{
			@SuppressWarnings("unchecked")
			List<Question> questions = (List<Question>)jdbct.query("Select * from Questions where Years=? order by Type, Qseq", 
					new Object[]{ year },
					new QuestionMapper());
			return questions;
		}catch(Exception e){
			System.out.println(e.getMessage());
			return null;
		}
	}
	
	public int getQuestionCountByYear(String year, String type){
		try{
			@SuppressWarnings("unchecked")
			int qcount = jdbct.queryForInt("Select count(*) from Questions where Years=? and Type=? ", 
					new Object[]{ year, type });
			return qcount;
		}catch(Exception e){
			System.out.println(e.getMessage());
			return 0;
		}
	}
	
	class QuestionMapper implements RowMapper{
		public Object mapRow(ResultSet rs, int rowNum) throws SQLException{
			Question question = null;
			try{
				question = new Question(rs.getInt("Qcid"), rs.getString("Qno"), rs.getString("Years"), rs.getString("Context")
						, rs.getString("Type")
						, rs.getDate("Createdate"), rs.getDate("Updatedate"));
			}catch(Exception e){
				System.out.println(e.getMessage());
			}
			return question;
		}
	}
}
